<?php
namespace Admin\Controller;
use Think\Controller;
/**
 * 文章管理
 */
class PostController extends BaseController
{
    /**
     * 文章列表
     * @return [type] [description]
     */
    public function index($key="")
    {
        if($key === ""){
            $model = D('PostView'); 
        }else{
            $where['post.name'] = array('like',"%$key%");
            $where['category.name'] = array('like',"%$key%");
            $where['_logic'] = 'or';
            $model = D('PostView')->where($where); 
        } 

        $count  = $model->where($where)->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,25);// 实例化分页类 传入总记录数和每页显示的记录数(25)

        $Page -> setConfig('prev','«');
        $Page -> setConfig('next','»');
        //$Page -> setConfig('theme',"<div class='defaultPager'>%UP_PAGE% %LINK_PAGE% %DOWN_PAGE%</div>");
        $Page -> setConfig('theme',"<ul class='pagination pagination-sm no-margin'> <li>%UP_PAGE%</li>  <li>%LINK_PAGE%</li>   <li>%DOWN_PAGE%</li>  </ul>");
        $show = $Page->show();// 分页显示输出
        $post = $model->limit($Page->firstRow.','.$Page->listRows)->where($where)->order('post.order_number DESC,post.id DESC')->select();

        $this->assign('post', $post);
        $this->assign('page',$show);
        $this->display();     
    }
    
    /**
     * 添加文章
     */
    public function add()
    {
        //默认显示添加表单
        if (!IS_POST) {
        	$nav=D('Category')->getTreeData('tree','order_number,id');
            
            $this->assign('nav',$nav);
            $this->display();
        }
        if (IS_POST) {
            //日期格式  月/日/年 10/06/2016
            $push_time = I('post.time');

            $year=((int)substr($push_time,6,4));//取得年份

            $day=((int)substr($push_time,3,2));//取得月份

            $month=((int)substr($push_time,0,2));//取得月份

            $time_str = mktime(0,0,0,$month,$day,$year);

             //date("Y/m/d",$time_str);  

            //如果用户提交数据
            $model = D("Post"); //用D操作，自动验证
            $info = $model->create();
            if (!$info) {
                $this->error($model->getError());
            }

            $info['time'] = $time_str;

            $thumb = $_FILES['thumb'];
            if ($thumb['name'] != '') {  //有提交图片
                $thumbpath = $this->uploadoneimg($thumb);
                $thumbpath = $thumbpath['savepath'].$thumbpath['savename'];
                $info['thumb'] = $thumbpath;
            }

            $result = $model->data($info)->add();
            if ($result) {
                //插入成功后，对标签处理
                $tags = I('post.tags'); //标签
                $db_tags = M('Tags');
                $db_post_tags = M('Post_tags');
                if (!empty($tags)) {    //标签处理
                    $tags = array_unique(explode(';',$tags));
                    foreach ($tags as $key => $tag) {  
                        //需要判断 如果存在则+1 不存在插入
                        $where['name'] = $tag;
                        $where['type'] = 0;
                        $tags_exist = $db_tags->where($where)->find();
                        if ($tags_exist) {
                            $result_add = $db_tags->where($where)->setField('num',$tags_exist['num']+1);
                            //新闻-标签表 插进关联id
                            $data_nt['post_id'] = $result; //新闻id
                            $data_nt['tag_id'] = $tags_exist['id']; //标签id
                            $result_nt = $db_post_tags->add($data_nt);
                        } else {
                            $data['name'] = $tag;
                            $data['num'] = 1;
                            $data['type'] = 0;
                            $inser_tags = $db_tags->add($data); //标签表插入标签，取插入的id
                            //新闻-标签表 插进关联id
                            $data_nt['post_id'] = $result; //新闻id
                            $data_nt['tag_id'] = $inser_tags; //标签id
                            $result_nt = $db_post_tags->add($data_nt);
                        }   
                    }   
                }
                $this->success("添加成功", U('post/index'));
            } else {
                $this->error("添加失败");
            } 
        }
    }

    /**
     * 复制文章
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function copy($id)
    {
        $id = intval($id);
        $info = M('post')->where("id= %d",$id)->find();

        //重组数据
        unset($info['id']);

        //复制的时候暂时除去标签
        unset($info['tags']);


        if ($info['thumb']) {
            $path = $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/upload/';
            $source = $info['thumb'];
            $destination = strstr($info['thumb'], '/',true).'/' .time().strstr($info['thumb'], '.');
            copy($path.$source , $path.$destination);
            $info['thumb'] = $destination;
        }

        if (M('post')->data($info)->add()) {
            $this->success("复制成功", U('post/index'));
        } else {
            $this->error("复制失败");
        } 
    }

    /**
     * 更新文章信息
     * @param  [type] $id [文章ID]
     * @return [type]     [description]
     */
    public function edit($id)
    {
    	$id = intval($id);
        //默认显示添加表单
        if (!IS_POST) {
            $nav=D('Category')->getTreeData('tree','order_number,id');
            $data=M('post')->find($id);

            $this->assign('nav',$nav);
            $this->assign('data',$data);
            $this->assign('thumb',$data['thumb']);
            $this->display();
        }
        if (IS_POST) {
            $model = D("Post");

            $info = $model->create();
            if (!$info) {
                $this->error($model->getError());
            }

            //日期格式  月/日/年 10/06/2016
            $push_time = I('post.time');

            $year=((int)substr($push_time,6,4));//取得年份

            $day=((int)substr($push_time,3,2));//取得月份

            $month=((int)substr($push_time,0,2));//取得月份

            $time_str = mktime(0,0,0,$month,$day,$year);

             //date("Y/m/d",$time_str); 

             $info['time'] = $time_str; 


            $thumb = $_FILES['thumb'];
            if ($thumb['name'] != '') {  //有提交新闻图片
                $thumbpath = $this->uploadoneimg($thumb);
                $thumbpath = $thumbpath['savepath'].$thumbpath['savename'];
                $info['thumb'] = $thumbpath;
            }

            //标签处理
            $db_tags = M('Tags');
            $db_post_tags = M('Post_tags');

            $map['id'] = $id; 

            $tags = $model->where($map)->getField('tags');
            $tags = explode(';',$tags);

            $tags_later_init = I('post.tags');
            $tags_later = array_unique(explode(';',$tags_later_init));

            //前后不全等，则进行操作，否则不进行
            //array_diff($tags,$tags_later) 减少的标签
            //array_diff($tags_lalter,$tags 新增的标签
            if (array_diff($tags_later,$tags) && !empty($tags_later_init)) {  //增加的中文标签
                $tags_add = array_diff($tags_later,$tags);
                        foreach ($tags_add as $key => $tag) {
                            //需要判断 如果存在则+1 不存在插入
                            $where['name'] = $tag;
                            $where['type'] = 0;
                            $tags_exist = $db_tags->where($where)->find();
                            if ($tags_exist) {
                                $result_add = $db_tags->where($where)->setField('num',$tags_exist['num']+1);
                                //新闻-标签表 插进关联id
                                $data_nt['post_id'] = $id; //新闻id
                                $data_nt['tag_id'] = $tags_exist['id']; //标签id
                                $result_nt = $db_post_tags->add($data_nt);
                            } else {
                                $data['name'] = $tag;
                                $data['num'] = 1;
                                $data['type'] = 0;
                                $inser_tags = $db_tags->add($data); //标签表插入标签，取插入的id
                                //新闻-标签表 插进关联id
                                $data_nt['post_id'] = $id; //新闻id
                                $data_nt['tag_id'] = $inser_tags; //标签id
                                $result_nt = $db_post_tags->add($data_nt);
                            }   
                        }       
            }
            if (array_diff($tags,$tags_later)) { //删除的中文标签
                $tags_delete = array_diff($tags,$tags_later);
                        foreach ($tags_delete as $key => $tag) {  
                            //需要判断 如果num等于1则删除  大于1则减一
                            $where['name'] = $tag;
                            $where['type'] = 0;
                            $tags_exist = $db_tags->where($where)->find();
                            if ($tags_exist['num'] > 1) {
                                $result_delete = $db_tags->where($where)->setField('num',$tags_exist['num']-1);
                            } else {
                                $result_delete = $db_tags->where($where)->delete();
                            }
                            $where_nt['post_id'] = $id;
                            $where_nt['tag_id'] = $tags_exist['id'];
                            $resutl_nt = $db_post_tags->where($where_nt)->delete();  
                        }           
            }
            if ($model->save($info)) {
                $this->success("更新成功", U('post/index'));
            } else {
                $this->error("更新失败");
            }          
        }
    }

    /**
     * 删除文章
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delete($id)
    {
        $id = intval($id);
        $model = M('post');

        //处理缩略图
        $thumb = $model->where("id= %d",$id)->getField('thumb');   
        $path = $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/upload/';
        delallimg($path,$thumb);//删除图片，包括文件路径

        //获取标签
        $tags = $model->where("id= %d",$id)->getField('tags');
        //处理标签
        if (!empty($tags)) {    //标签处理
            $db_tags = M('Tags');
            $tags = explode(';',$tags);
            foreach ($tags as $key => $tag) {  
                //需要判断 如果num等于1则删除  大于1则减一
                $where['name'] = $tag;
                $where['type'] = 0;
                $tags_exist = $db_tags->where($where)->find();
                if ($tags_exist['num'] > 1) {
                    $result_delete = $db_tags->where($where)->setField('num',$tags_exist['num']-1);
                } else {
                    $result_delete = $db_tags->where($where)->delete();
                }   
            }   
        }       
                
        $result = $model->where("id= %d",$id)->delete();
        if($result){
            $db_post_tags = M('Post_tags');  //删除文章-标签表的记录
            $where_nt['post_id'] = $id;
            $resutl_nt = $db_post_tags->where($where_nt)->delete();
            $this->success("删除成功", U('post/index'));
        }else{
            $this->error("删除失败");
        }
    }

    /**
     * 删除文章缩略图
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delthumb() {
        $id = intval(I('get.id'));
        if ($id) {
            $map['id'] = $id;
            $model=M('post');
            $thumb = $model->where($map)->getField('thumb');
            $path = $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/upload/';
            delallimg($path,$thumb); //删除图片，包括文件路径
            if ($model->where($map)->setField('thumb','')) {
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }
    }

    /**
     * 删除所选的文章
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delAll() {   //ajax删除选中的新闻   
        $id = array();
        $id = I('post.new_id'); 
        $new_id = implode(',',$id);
        $model = M('Post');

        foreach ($id as $value) { //删除所选新闻的图片路径  和标签
            $where['id'] = $value;

            //获取缩略图
            $thumb=$model->where($where)->getField('thumb');
            if ($thumb) {
                $path = $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/upload/';
                delallimg($path,$thumb);
            }

            //获取中英标签
            $tags = $model->where($where)->getField('tags');
            //处理标签
            if (!empty($tags)) {    //标签处理
                $db_tags = M('Tags');
                $tags = explode(';',$tags);
                foreach ($tags as $key => $tag) {  
                    //需要判断 如果num等于1则删除  大于1则减一
                    $where_tag['name'] = $tag;
                    $where_tag['type'] = 0;
                    $tags_exist = $db_tags->where($where_tag)->find();
                    if ($tags_exist['num'] > 1) {
                        $result_delete = $db_tags->where($where_tag)->setField('num',$tags_exist['num']-1);
                    } else {
                        $result_delete = $db_tags->where($where_tag)->delete();
                    }   
                }   
            }

        }

        $map['id']  = array('in',$new_id);
        $result = $model->where($map)->delete();
        if ($result) {
            //删除文章-标签表的记录
            $db_post_tags = M('Post_tags');
            $where_nt['post_id'] = array('in',$new_id);
            $resutl_nt = $db_post_tags->where($where_nt)->delete();
            $this->ajaxReturn("删除成功");
        }  else {
            $this->ajaxReturn("删除失败");  
        }         
    }

    /**
     * 排序
     */
    public function order(){
        $data=I('post.');
        D('Post')->orderData($data);
        $this->success('排序成功',U('Admin/Post/index'));
    }
}
